layui.use(['table', 'admin', 'ax', 'func', 'layer'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;
    var layer = layui.layer;


    /**
     * 接口审批列表管理
     */
    var Interfaceapproval = {
        tableId: "interfaceapprovalTable"
    };

    /**
     * 初始化表格的列
     */
    Interfaceapproval.initColumn = function () {
        return [[
            {type: 'checkbox', width: 35, align: 'right'},
            {field: 'id', hide: true, title: 'id'},
            {
                field: 'rank',
                title: '全选',
                align: 'left',
                templet: '#rank',
                style: 'background-color:#ffffff',
                width: 120
            },
            {field: 'userId', sort: true, title: '用户id', hide: true},
            {
                field: 'content', sort: false, title: '申请内容',
                style: 'background-color:#ffffff',
                align: 'center',
                templet: function (res) {
                    if (res.content == 1) {
                        return '数据对比接口'
                    } else if (res.content == 2) {
                        return '接口定制'
                    }
                }
            },
            {
                field: 'department', sort: false, title: '单位',
                style: 'background-color:#ffffff',
                align: 'center'
            },
            {
                field: 'system', sort: false, title: '应用系统',
                style: 'background-color:#ffffff',
                align: 'center'
            },
            {
                field: 'servicetype', sort: false, title: '服务类型',
                style: 'background-color:#ffffff',
                align: 'center',
                templet: function (res) {
                    if (res.servicetype == 1) {
                        return '数据库服务'
                    }
                    // else if (res.servicetype == 2) {
                    //     return '平台类型'
                    // } else if (res.servicetype == 3) {
                    //     return '其他类型'
                    // }
                }
            },
            {
                field: 'idescribe', sort: false, title: '接口描述',
                style: 'background-color:#ffffff',
                align: 'center'
            },
            {
                field: 'state', sort: false, title: '状态',
                style: 'background-color:#ffffff',
                align: 'center',
                templet: function (res) {
                    if (res.state == 0) {
                        return '<span style="color:#FF4500;">' + '待处理' + '</span>'
                    } else if (res.state == 1) {
                        return '<span style="color:greenyellow">' + '已批准' + '</span>'
                    } else if (res.state == 2) {
                        return '<span style="color:#c00;">' + '已驳回' + '</span>'
                    } else if (res.state == 3) {
                        return '<span style="color:#008000;">' + '已完成' + '</span>'
                    }
                }
            },
            {field: 'remarks', sort: true, title: '备注', hide: true},
            {field: 'revision', sort: true, title: '乐观锁', hide: true},
            {field: 'createdBy', sort: true, title: '创建人', hide: true},
            {field: 'createdTime', sort: true, title: '创建时间', hide: true},
            {field: 'updatedBy', sort: true, title: '更新人', hide: true},
            {field: 'updatedTime', sort: true, title: '更新时间', hide: true},
            {
                align: 'right', toolbar: '#tableBar', title: '',
                style: 'background-color:#ffffff'
            }
        ]];
    };

    /**
     * 点击查询按钮
     */
    Interfaceapproval.search = function () {
        var queryData = {};

        // queryData['id'] = $('#id').val();
        // queryData['userId'] = $('#userId').val();
        queryData['content'] = $('#checkContent input[name="content"]:checked ').val();
        queryData['department'] = $('#department').val();
        queryData['system'] = $('#system').val();
        queryData['servicetype'] = $('#servicetype').val();
        // queryData['idescribe'] = $('#idescribe').val();
        queryData['state'] = $('#state').val();

        table.reload(Interfaceapproval.tableId, {
            where: queryData, page: {curr: 1}
        });
    };


    /**
     * 点击查看详情
     *
     * @param data 点击按钮时候的行数据
     */
    Interfaceapproval.openEditDlg = function (data) {
        // console.log(data)
        if (data.content == 2) {
            if (data.state != 3) {
                layer.open({
                    title: '',
                    type: 2,
                    area: ['80%', '80%'],
                    content: Feng.ctxPath + '/interfaceapproval/edit?id=' + data.id,
                    // tableId: Interfaceapproval.tableId,
                    end: function () {
                        table.reload(Interfaceapproval.tableId)
                    },
                });
            } else {
                sessionStorage.setItem("interfaceapprovalId", data.id)
                layer.open({
                    title: '',
                    content: Feng.ctxPath + '/interfaceapproval/interfaceCustomDone',
                    type: 2,
                    area: ['80%', '80%'],
                    end: function () {
                        table.reload(Interfaceapproval.tableId)
                    },
                });
            }
        } else {
            sessionStorage.setItem("id", data.id);
            layer.open({
                title: '',
                type: 2,
                area: ['80%', '80%'],
                content: Feng.ctxPath + '/interfaceapproval/editComparison',
                // tableId: Interfaceapproval.tableId,
                // cancel: function () {
                //     location.reload();
                // },
                end: function () {
                    table.reload(Interfaceapproval.tableId)
                },
            });
        }
    };


    /**
     * 点击完成
     *
     * @param data 点击按钮时候的行数据
     */
    Interfaceapproval.onDoneItem = function (data) {
        // console.log(data)
        sessionStorage.setItem("addInterface", 'addInterface')
        sessionStorage.setItem('data', JSON.stringify(data))
        func.open({
            title: '',
            content: Feng.ctxPath + "/interfacelist/add",
            maxmin: true,
            type: 2,
            success: function (layero) {
                //移除最小化
                layero.find('.layui-layer-min').remove();
            },
        })
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + Interfaceapproval.tableId,
        url: Feng.ctxPath + '/interfaceapproval/list',
        page: true,
        height: "full-158",
        cellMinWidth: 100,
        skin: 'line',
        even: false,
        cols: Interfaceapproval.initColumn(),
        done: function (res, curr, count) {
            $('tr').css('background-color', '#ffffff');
            table_data = res.data;
            // console.log(table_data)
            var status = "";
            for (var i in table_data) {
                var item = table_data[i];
                // console.log(item)
                if (item.state == 1 || item.state == 2 || item.state == 3) {
                    // checkbox 根据条件设置不可选中
                    $('.layui-table tr[data-index=' + i + '] input[type="checkbox"]').prop('disabled', true);
                    $(".layui-table tr[data-index=" + i + "] input[type='checkbox']").next().addClass('layui-btn-disabled');
                    status = "1";// 隐藏表头全选判断状态
                }
            }
            //判断条件
            if (status == "1") {
                // 根据条件移除全选 checkbox
                $('th[data-field=0] div').replaceWith('<div class="layui-table-cell laytable-cell-5-0-0"><span></span></div>');
            } else {
                //翻页显示全选按钮 checkbox
                $('th[data-field=0] div').replaceWith('<div class="layui-table-cell laytable-cell-1-0-0 laytable-cell-checkbox"><input type="checkbox" name="layTableCheckbox" lay-skin="primary" lay-filter="layTableAllChoose"><div class="layui-unselect layui-form-checkbox" lay-skin="primary"><i class="layui-icon layui-icon-ok"></i></div></div>');
            }
        }
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        Interfaceapproval.search();
    });


    //自定义数组
    //获取表格复选框内的id
    var table_data = new Array();
    var ids = new Array();
    table.on('checkbox(' + Interfaceapproval.tableId + ')', function (obj) {
        // console.log(obj)
        if (obj.checked == true) {
            if (obj.type == 'one') {
                ids.push(obj.data.id);
            } else {
                for (var i = 0; i < table_data.length; i++) {
                    ids.push(table_data[i].id);
                }
            }
        } else {
            if (obj.type == 'one') {
                for (var i = 0; i < ids.length; i++) {
                    if (ids[i] == obj.data.id) {
                        // ids.remove(i);用这个方法会报错not a function
                        //ids.pop(); 建议用这个
                        ids.splice(i, 1);
                    }
                }
            } else {
                for (var i = 0; i < ids.length; i++) {
                    for (var j = 0; j < table_data.length; j++) {
                        if (ids[i] == table_data[j].id) {
                            // ids.remove(i);
                            // ids.pop();
                            ids.splice(i, 1);
                        }
                    }
                }
            }
        }
        // console.log(ids);
        // console.log(table_data);
    });

    //点击批准或者驳回按钮
    $("#btnApprove").click(function () {
        if (ids.length == 0) {
            Feng.error('请先选择数据')
            return;
        }
        $.ajax(Feng.ctxPath + '/interfaceapproval/approve', {
            data: {
                ids: ids
            },
            traditional: true,
            success: function (res) {
                // console.log(res)
                if (res == ids.length) {
                    Feng.success('批准成功')
                    // location.reload()
                    table.reload(Interfaceapproval.tableId)
                }
            },
            error: function () {
                Feng.error('批准失败')
            }
        })
    })

    $("#btnReject").click(function () {
        if (ids.length == 0) {
            Feng.error('请先选择数据')
            return;
        }
        $.ajax(Feng.ctxPath + '/interfaceapproval/reject', {
            data: {
                ids: ids
            },
            traditional: true,
            success: function (res) {
                // console.log(res)
                if (res == ids.length) {
                    Feng.success('驳回成功')
                    // location.reload()
                    table.reload(Interfaceapproval.tableId)
                }
            },
            error: function () {
                Feng.error('驳回失败')
            }
        })
    })

    // 工具条点击事件
    table.on('tool(' + Interfaceapproval.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            Interfaceapproval.openEditDlg(data);
        } else if (layEvent === 'done') {
            Interfaceapproval.onDoneItem(data);
        }
    });
});
